package io.github.mymonstercat.tools.text;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author wry
 */
@Slf4j
public class TextParsingDispatcher {

    private static final String JSON_REGEX = "\\{([^}]*)}";
    private static final Pattern JSON_PATTERN = Pattern.compile(JSON_REGEX);

    /**
     * 解析json格式或markdown格式的列表数据
     *
     * @param text 文本
     * @return List<String> 单个文本块解析结果，包含多行数据
     */
    public static List<String> parse(String text) {
        List<String> jsonBlocks = extractJsonBlocks(text);
            if (!jsonBlocks.isEmpty()) {
                /*return jsonBlocks.stream()
                        .map(JsonBottomLevelElementExtractor::extractBottomLevelElementsFromJson)
                        .flatMap(List::stream)
                        .collect(Collectors.toList());*/
                return jsonBlocks;
            }

        // json解析不通过, 尝试解析带序号的文本
        return SequenceTextParser.parse(text)
                .orElse(Collections.emptyList());
    }

    private static List<String> extractJsonBlocks(String text) {
        List<String> jsonBlocks = new ArrayList<>();
        jsonBlocks.add(text);

        /*Matcher matcher = JSON_PATTERN.matcher(text);

        while (matcher.find()) {
            jsonBlocks.add(text.substring(matcher.start(0), matcher.end(0)));
        }*/
        return jsonBlocks;
    }

}
